import * as vscode from 'vscode';
import { Uri } from 'vscode';
import * as fs from 'fs';
import { CMD } from './cmd';
import ResPickHelper from './utils/ResPickHelper';
import { LayoutPanel } from './LayoutPanel';
import * as path from 'path';

export default class RequestHandle {
    private mRequest;
    private mResponse;
    private mData;

    private cmdMapping = new Map<string, Function>([
        [CMD.exportCodeAsFile, () => this.exportCodeAsFile()],
        [CMD.build, () => this.runScript()],
        [CMD.run, () => this.runScript()],
        [CMD.selectScript, () => this.selectScript()],
        [CMD.savePage, () => this.savePage()],
        [CMD.getPageData, () => this.getPageData()],
        [CMD.getActFileName, () => this.getActFileName()],
    ]);

    async handel(request, response, next) {
        this.mRequest = request;
        this.mResponse = response;
        this.mData = request?.body?.data;

        const cmd = this.mRequest.body.cmd;
        if (!this.cmdMapping.has(cmd)) {
            process.nextTick(function(){
                next(new Error(`command[${cmd}] not found!`));
            });
            return;
        }
        
        const result = await this.cmdMapping.get(cmd)!();
        if (result instanceof Buffer) {
            this.mResponse.end(result);
            return;
        }
        this.mResponse.end(result ? JSON.stringify(result) : '');
    }


    exportCodeAsFile() {
        if (!this.mData?.name || !this.mData?.code) {
            return;
        }
        const options = {defaultUri: Uri.file(this.mData.name)};
        vscode.window.showSaveDialog(options).then((uri) => {
            if (!uri) {
                return;
            }
            fs.writeFileSync(uri.fsPath, this.mData.code);
        }, e => {
            console.error(e);
        });
    }

    runScript() {
        if (!this.mData) {
            console.warn("script is empty");
            return;
        }

        const terminal = vscode.window.createTerminal({
            hideFromUser: false, 
            shellPath: 'C:\\Windows\\System32\\cmd.exe'
        });
        terminal.show();
        terminal.sendText(`${this.mData}`);
    }

    async selectScript() {
        const file = await ResPickHelper.pickFile(false, { 'file': ['bat'] }, Uri.file(''));
        if (file && file[0]) {
            return file[0].fsPath;
        }
    }

    savePage() {
        if (!this.mData) {
            return;
        }

        let layoutPath = LayoutPanel.getInstance()?.getActiveUri()!;
        fs.writeFileSync(layoutPath.fsPath, JSON.stringify(this.mData));
        return true;
    }

    getPageData() {
        let layoutPath = LayoutPanel.getInstance()?.getActiveUri()!;
        return fs.readFileSync(layoutPath.fsPath);
    }

    getActFileName() {
        let layoutPath = LayoutPanel.getInstance()?.getActiveUri()!;
        return path.basename(layoutPath.fsPath, '.lty');
    }
}